import { ApiProperty } from '@nestjs/swagger'
import { BaseEntity, Column, CreateDateColumn, Entity, Index, JoinColumn, ManyToOne, PrimaryGeneratedColumn } from 'typeorm'

import { UserEntity } from '~/modules/user/user.entity'
import { DeviceEntity } from '../device/device.entity'

@Entity({ name: 'health_user_data' })
@Index(['userId', 'type', 'ts'], { unique: true })
@Index(['ts'])
export class UserDataEntity extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number

  @Column({ name: 'user_id', nullable: true, comment: '用户ID' })
  @ApiProperty({ description: '用户ID' })
  userId: number

  @Column({ nullable: true, comment: '设备ID' })
  @ApiProperty({ description: '设备ID' })
  uid: string

  @Column({ nullable: true, comment: '数据类型' })
  @ApiProperty({ description: '数据类型' })
  type: number

  @Column({ nullable: true, comment: '时间戳' })
  @ApiProperty({ description: '时间戳' })
  ts: Date

  @Column({ nullable: true, comment: '数据', type: 'json' })
  @ApiProperty({ description: '数据' })
  data: any

  @CreateDateColumn({ name: 'created_at' })
  @ApiProperty({ description: '创建时间' })
  createdAt: Date

  @ManyToOne(() => UserEntity, user => user.id, {
    onDelete: 'CASCADE',
  })
  @JoinColumn({ name: 'user_id', referencedColumnName: 'id' })
  user: UserEntity

  @ManyToOne(() => DeviceEntity, device => device.uid, {
    onDelete: 'SET NULL',
  })
  @JoinColumn({ name: 'uid', referencedColumnName: 'uid' })
  device: DeviceEntity
}
